package com.qianbei.common;

import android.content.Context;
import android.graphics.Rect;
import android.support.v4.widget.SwipeRefreshLayout;
import android.util.AttributeSet;
import android.view.MotionEvent;
import android.view.View;

/**
 *
 * 解决ListView中增加headview造成横向滑动，焦点冲突的问题。
 *
 * @author jiaowenzheng
 * Created by user on 16/6/3.
 */
public class MySwipeRefreshLayout extends SwipeRefreshLayout {

    private LoadMoreListView mLoadMoreListView;
    private View mListViewHeaderView;
    private Rect mRect = new Rect();


    public MySwipeRefreshLayout(Context context, AttributeSet attrs) {
        super(context, attrs);
    }


    @Override
    protected void onFinishInflate() {
        super.onFinishInflate();
        if (getChildCount() == 2){
            View view = getChildAt(1);
            if (view instanceof LoadMoreListView){
                mLoadMoreListView = (LoadMoreListView)view;
            }
        }

    }

    public void setListViewHeader(View view){
        this.mListViewHeaderView = view;
    }

    private float dowX;
    private float dowY;
    private boolean isDispatch = false;

    @Override
    public boolean dispatchTouchEvent(MotionEvent e) {

        if (mListViewHeaderView == null){
            return super.dispatchTouchEvent(e);
        }

        int x = (int) e.getX();
        int y = (int) e.getY();

//        if (mListViewHeaderView.isShown() && e.getAction() == MotionEvent.ACTION_DOWN){
//            mListViewHeaderView.getLocalVisibleRect(mRect);
//        }

//        if(mRect.contains(x,y) && mListViewHeaderView.isShown()){
//            return mLoadMoreListView.dispatchTouchEvent(e);
//        }else{
//            return super.dispatchTouchEvent(e);
//        }

        if (!mListViewHeaderView.isShown()){
            return super.dispatchTouchEvent(e);
        }

        switch (e.getAction()){
            case MotionEvent.ACTION_DOWN:
                dowX = e.getX();
                dowY = e.getY();
                break;
            case MotionEvent.ACTION_MOVE:
                float moveX = e.getX();
                float moveY = e.getY();

                float offsetX = Math.abs(moveX - dowX);
                float offsetY = Math.abs(moveY - dowY);

                if (offsetX > offsetY){
                    isDispatch = true;
                   return mLoadMoreListView.dispatchTouchEvent(e);
                }else{
                    isDispatch = false;
                   return super.dispatchTouchEvent(e);
                }
            case MotionEvent.ACTION_UP:
                if (isDispatch){
                    mListViewHeaderView.dispatchTouchEvent(e);
                }
                isDispatch = false;
                break;

        }

        return super.dispatchTouchEvent(e);

    }
}
